package com.enki.adminplatform.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.enki.adminplatform.common.Const;
import com.enki.adminplatform.common.Result;
import com.enki.adminplatform.common.ResultCodeEnum;
import com.enki.adminplatform.exception.EnkiException;
import com.enki.adminplatform.util.RedisUtil;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.UUID;

/**
 * @author yinyin
 * @create 2021/07/26 下午 5:46
 */
@Api("权限校验")
@RestController
@RequestMapping("/sys/auth")
public class AuthController {
    @Autowired
    Producer producer;
    @Autowired
    RedisUtil redisUtil;

    @ApiOperation("生成验证图片")
    @PostMapping("getCaptcha")
    public Result captcha(){
        try {
            String key = UUID.randomUUID().toString();
            String code = producer.createText();

            BufferedImage image = producer.createImage(code);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", outputStream);
            BASE64Encoder encoder=new BASE64Encoder();
            String str="data:image/jpeg;base64,";

            String base64Img=str+encoder.encode(outputStream.toByteArray());

            redisUtil.hset(Const.CAPTCHA_KEY,key,code,120);

            return  Result.ok().data("key",key).data("img",base64Img);
        } catch(Exception e){
            throw new EnkiException(ResultCodeEnum.PIC_GENERATION_ERROR);
        }
    }
}
